package com.lightkits.wms.domain.retirelib.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lightkits.common.db.entity.FndEventTypeBase;
import com.lightkits.common.db.entity.event.BdEvent;
import com.lightkits.common.db.entity.event.BdEventRecord;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.model.CheckResult;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.object.ParseUtil;
import com.lightkits.framework.soa.client.id.GetGlobalIDRequestType;
import com.lightkits.framework.soa.client.id.GetGlobalIDResponseType;
import com.lightkits.framework.soa.client.id.IDServiceClient;
import com.lightkits.wms.domain.allot.impl.CreateEventParamsServiceImpl;
import com.lightkits.wms.domain.retireLib.CreateRetireEventParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;

/**
 * @author jing.wei@hand-china.com
 * @date 2019/6/10 17:38
 **/
@Service
public class CreateRetireEventParamsImpl implements CreateRetireEventParams {
    private static final Logger LOGGER = LoggerFactory.getLogger(CreateEventParamsServiceImpl.class);

    @Autowired
    private IDServiceClient idAdapterService;

    /**
     * 创建领料单头事件
     *
     * @param orgId    组织Id
     * @param workerId 员工Id
     * @return
     */
    @Override
    public CheckResult<BdEvent> createEvent(String orgId, String workerId) {
        CheckResult<BdEvent> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        // TODO: 事务隔离范围过大
        GetGlobalIDRequestType idRequest = new GetGlobalIDRequestType();
        idRequest.setCount(1);
        GetGlobalIDResponseType idResponse = idAdapterService.getGlobalId(idRequest);
        Iterator<Long> sfIds = idResponse.getIds().iterator();
        BdEvent event = new BdEvent();
        try {
            //获取事件类型Id
            FndEventTypeBase eventTypeBase = new FndEventTypeBase().selectOne(new EntityWrapper()
                    .eq(FndEventTypeBase.EVENT_TYPE_CODE, "SCRAP_DOC_CREATE"));
            event.setEventTypeId(eventTypeBase.getId());
            event.setEventTypeCode(eventTypeBase.getEventTypeCode());
            event.setEventRequestId(sfIds.next());
            if (!ObjectUtil.isNullOrEmpty(workerId)) {
                event.setWorkerId(ParseUtil.tryLongWithException(workerId));
            }
            if (!ObjectUtil.isNullOrEmpty(orgId)) {
                event.setOrganizationId(ParseUtil.tryLongWithException(orgId));

            }
            event.setCalendarDay(new Date());
            checkResult.setData(event);
        } catch (Exception e) {
            LOGGER.error("createEvent.error", e);
            throw new LightKitsBizException(e);
        }
        checkResult.setData(event);
        return checkResult;
    }

    /**
     * 事件快照的创建
     *
     * @param objectType     事件对象类型
     * @param keyValue       事件关键值
     * @param objectId       事件对象ID
     * @param recordType     事件记录类型
     * @param snapShotRecord 事件快照记录，JSON格式保存
     * @return
     **/
    @Override
    public CheckResult<BdEventRecord> createEventRecord
    (String objectType,
     String keyValue,
     Long objectId,
     String recordType,
     String snapShotRecord) {
        CheckResult<BdEventRecord> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        BdEventRecord eventRecord = new BdEventRecord();
        try {
            eventRecord.setObjectId(objectId);
            eventRecord.setObjectType(objectType);
            eventRecord.setRecordType(recordType);
            eventRecord.setKeyValue(keyValue);
            eventRecord.setSnapshotRecord(snapShotRecord);
            checkResult.setData(eventRecord);
        } catch (Exception e) {
            LOGGER.error("createEventRecord.error", e);
            throw new LightKitsBizException(e);
        }
        return checkResult;
    }

//    /**
//     * 创建事务
//     *
//     * @param lineList 领料单行
//     * @param model    事务参数
//     * @return
//     */
//    @Override
//    public CheckResult<List<BdTransaction>> createTranscation(List<WmRequestLine> lineList, TransModel model
//    ) {
//        CheckResult<List<BdTransaction>> checkResult = new CheckResult<>();
//        List<BdTransaction> transList = new ArrayList<>();
//        checkResult.setSuccessful(true);
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//
//        try {
//            // TODO: 事务隔离范围过大
//            GetGlobalIDRequestType idRequest = new GetGlobalIDRequestType();
//            idRequest.setCount(lineList.size());
//            GetGlobalIDResponseType idResponse = idAdapterService.getGlobalId(idRequest);
//            Iterator<Long> sfIds = idResponse.getIds().iterator();
//            FndTransactionTypeBase base = new FndTransactionTypeBase()
//                    .selectById(model.getTransTypeId());
//            FndDocumentTypeBase documentTypeBase = new FndDocumentTypeBase().selectOne(new EntityWrapper()
//                    .eq(FndDocumentTypeBase.DOCUMENT_TYPE_CODE, "WH_SCRAP"));
//            lineList.forEach(line -> {
//                BdTransaction trans = new BdTransaction();
//                trans.setTransactionTypeId(model.getTransTypeId());
//                trans.setTransactionTypeCode(base.getTransactionTypeCode());
//                trans.setOrganizationId(model.getOrgId());
//                trans.setItemId(line.getItemId());
//                trans.setTransactionUom(line.getUom());
//                trans.setTransactionQty(line.getApplyQty());
//                trans.setTransactionDate(new Date());
//                trans.setDocumentTypeCode("WH_SCRAP");
//                trans.setDocumentTypeId(documentTypeBase.getId());
//                trans.setDocumentId(line.getRequestId());
//                trans.setDocumentLineId(line.getId());
//                trans.setDocumentNum(model.getHeaderNum());
//                trans.setWarehouseId(line.getWarehouseId());
//                trans.setLocationId(line.getLocationId());
//                trans.setWorkerId(model.getWorkerId());
//                FndWorker worker = new FndWorker().selectById(model.getWorkerId());
//                trans.setWorkerNumber(worker.getWorkerNumber());
//                trans.setEventRequestId(model.getEventRequestId());
//                trans.setRemark(line.getRemark());
//                trans.setTransactionReasonCode(model.getMoveTypeId());
//                transList.add(trans);
//            });
//            checkResult.setData(transList);
//        } catch (Exception e) {
//            LOGGER.error("createTranscation.error", e);
//            throw new LightKitsBizException(e);
//        }
//        return checkResult;
//
//    }
}

